from PyQt5.QtGui import QPainter
from PyQt5.QtWidgets import QWidget, QApplication, QMenu
from PyQt5.QtCore import Qt, QTimer, QEvent


class Widget(QWidget):
    def __init__(self, parent=None):
        super(Widget, self).__init__(parent)
        self.justDoubleClicked = False
        self.key = ""
        self.text = ""
        self.message = ""

    #
    def paintEvent(self, event):
        text = self.text
        i = text.find("\n\n")  # 如果找不到，find返回-1，index返回exception
        if i >= 0:
            text = text[:i]
        if self.key:
            text += "\n\nYou pressed:%s" % self.key
        painter = QPainter(self)
        painter.setRenderHint(QPainter.TextAntialiasing)
        painter.drawText(self.rect(), Qt.AlignCenter, text)
        if self.message:
            painter.drawText(self.rect(), Qt.AlignBottom | Qt.AlignCenter, self.message)
            QTimer.singleShot(5000, self.clear)
            QTimer.singleShot(5000, self.update)

    def clear(self):
        self.message = ""

    def resizeEvent(self, event):
        self.text = "Resized to Qsize({},{})".format(event.size().width(), event.size().height())
        self.update()

    def keyPressEvent(self, event):
        # key()返回键的编码
        # modifiers()返回shift,ctrl,alt的状态
        self.key = ""
        if event.key() == Qt.Key_Home:
            self.key = "Home"
        elif event.key() == Qt.Key_End:
            self.key = "End"
        elif event.key() == Qt.Key_PageUp:
            if event.modifiers() & Qt.ControlModifier:
                self.key = "Ctrl+PageUP"
            else:
                self.key = "PageUp"
        elif event.key() == Qt.Key_PageDown:
            if event.modifiers() & Qt.ControlModifier:
                self.key = "Ctrl+PageDown"
            else:
                self.key = "PageDown"
        elif Qt.Key_A < event.key() <= Qt.Key_Z:
            if event.modifiers() & Qt.ShiftModifier:
                self.key = "Shift+"
            self.key += event.text()

        if self.key:
            self.key = self.key
            self.update()
        else:
            QWidget.keyPressEvent(self, event)

    def contextMenuEvent(self, event):
        menu = QMenu()
        oneAction = menu.addAction("&One")
        twoAction = menu.addAction("&Two")
        oneAction.triggered.connect(self.one)
        twoAction.triggered.connect(self.two)

        if not self.message:
            menu.addSeparator()
            threeAction = menu.addAction("Thre&e")
            threeAction.triggered.connect(self.three)
        menu.exec(event.globalPos())

    def one(self):
        self.message = "Menu option One"
        self.update()

    def two(self):
        self.message = "Menu option Two"
        self.update()

    def three(self):
        self.message = "Menu option Three"
        self.update()

    def mouseDoubleClickEvent(self, event):
        self.justDoubleClicked = True
        self.text = "Double_clicked"
        self.update()

    def mouseReleaseEvent(self, event):
        if self.justDoubleClicked:
            self.justDoubleClicked = False
        else:
            self.setMouseTracking(not self.hasMouseTracking())
            if self.hasMouseTracking():
                self.text = "Mouse tracking is on.\n Try moving the mouse\n Single click to swithc it off"
            else:
                self.text = "Mouse tracking is off.\n Single click to swithc it on"
            self.update()

    def mouseMoveEvent(self, event):
        if not self.justDoubleClicked:
            globalPos = self.mapToGlobal(event.pos())
            self.text = "The mouse is at \n Qpoint(%d ,%d) in widget coords,and \n QPoint(%d,%d) in screen coords" % (
                event.pos().x(), event.pos().y(), globalPos.x(), globalPos.y())
            self.update()

    def event(self, event):
        if event.type() == QEvent.KeyPress and event.key() == Qt.Key_Tab:
            self.key = "Tab captured in event()"
            self.update()
            return True
        return QWidget.event(self, event)
    # def one(self):
    #     self.message="You select action one"
    #     self.update()
    # def two(self):
    #     pass
    # def three(self):
    #     pass


if __name__ == '__main__':
    import sys

    app = QApplication(sys.argv)
    form = Widget()
    form.show()
    sys.exit(app.exec())
